import simtester.cloud.Cloud
import simtester.server.Category
import simtester.server.Instance
import simtester.server.User
import simtester.server.Team
import simtester.server.Type

class BootStrap {
    def grailsApplication

    def init = { servletContext ->
        Instance.list().each {
            it.delete()
        }
        
        if (grailsApplication.config.test.cloud == 'local') {
            def dirs = new File(grailsApplication.config.test.env).listFiles()
            dirs.each {
                new AntBuilder().delete(dir: it)
            }
        }
        
        def agentPackage = grailsApplication.parentContext.getResource('classpath:resources/agent.jar').getFile().canonicalPath
        agentPackage = new File(agentPackage)
        
        def config = grailsApplication.config
        Cloud cloud = new Cloud(type:     config.test.cloud,
                                env:      config.test.env,
                                creds:    config.aws.credentialsfile,
                                endpoint: config.aws.endpoint,
                                key:      config.aws.key)
        
        def threads = []
        def numInstances = 10
        def instances = new Object[numInstances]
        numInstances.times { i ->
            if (config.test.cloud == 'local') {
                instances[i] = cloud.createBlankTestAgent(
                    agentpkg:  agentPackage,
                    url:       "${grailsApplication.config.grails.serverURL}/")
            } else {
                threads << Thread.start {
                    instances[i] = cloud.createBlankTestAgent(
                        agentpkg: agentPackage,
                        url:      "${grailsApplication.config.grails.serverURL}/")
                }
            }
        }
        
        threads.each { it.join() }
        instances.each {
            new Instance(cloudId: it.id, amiId: it.amiId, type: it.type, status: 'free').save(failOnError: true)
        }

		def team = Team.findByName('unassigned')

		if (!team) {
			team = new Team(name: 'unassigned')
			team.save()
		}
		
		// create admin user account
		def usr = User.findByUsername('admin')
		if ( !usr ) {
			usr = new User(username: 'admin', password: 'admin'.encodeAsMD5(), adminRole: true)
			team.addToUsers(usr)
			team.save(failOnError:true)
		}
		
        ['Load', 'GUI'].each {
            if (!Type.findByName(it)) {
                new Type(name: it).save()
            }
        }
        
        ['product', 'project'].each {
            if (!Category.findByName(it)) {
                new Category(name: it).save()
            }
        }
    }
    def destroy = {
        def instances = Instance.list()
        def instanceIds = instances.collect { it.cloudId }
        
        def config = grailsApplication.config
        Cloud cloud = new Cloud(type:     config.test.cloud,
                                env:      config.test.env,
                                creds:    config.aws.credentialsfile,
                                endpoint: config.aws.endpoint,
                                key:      config.aws.key)
        cloud.removeInstances(instanceIds)
        
        instances.each { it.delete() }
	}
}
